﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace FriendlyFire.UserControls
{
    public partial class Home : UserControl
    {
        //vars
        private FriendlyFire myParent;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ffHelper">reference to friendly fire helper</param>
        public Home(FriendlyFire parent)
        {
            InitializeComponent();
            myParent = parent;
            //friendConnectWorker.RunWorkerAsync();

            shoutBox.Height = myParent.ClientRectangle.Height - 160;
            txtShoutMsg.Width = this.ClientRectangle.Width - (150) - lstFriendChat.ClientRectangle.Width - 15;
            LoadShoutBox();                                 // 150 is the left side

            lstLists.DisplayMember = "Value";
            lstLists.ValueMember = "Key";
            Dictionary<long,string> ds = myParent.ffHelper.DBHelper.GetPlayLists();
            lstLists.DataSource = (ds.Count > 0 ? ds.ToList() : null);
        }

        #region Custom Paint
        /// <summary>
        /// Overrides the paint function to draw a gradient and enable double buffering to prevent flickering on screen resize
        /// </summary>
        /// <param name="sender">Object sending the event</param>
        /// <param name="e">any event arguments that need to be passed</param>
        private void Home_Paint(object sender, PaintEventArgs e)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            myParent.ffHelper.DrawDefaultBackGroundGradient(e.Graphics, ClientRectangle);
        }
        #endregion

        #region Resize Fix
        /// <summary>
        /// Event to make sure all windows on the user control display properly when the form is resized
        /// </summary>
        /// <param name="sender">Object sending the event</param>
        /// <param name="e">any event arguments that need to be passed</param>
        private void Home_Resize(object sender, EventArgs e)
        {
            if (myParent.ClientRectangle.Height > 160)
            {
                shoutBox.Height = myParent.ClientRectangle.Height - 160;
            }
            if (this.ClientRectangle.Width > ((150) + lstFriendChat.ClientRectangle.Width + 15))
            {
                txtShoutMsg.Width = this.ClientRectangle.Width - (150) - lstFriendChat.ClientRectangle.Width - 15;
            }
        }
        #endregion

        #region Async Connect to Friends on startup.

        /// <summary>
        /// Async worker.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       // public void friendConnectWorker_DoWork(object sender, DoWorkEventArgs e)
        //{
            //TODO replace with new DB layer
            /*
            SubSonic.Generated.FriendXCollection friends = null;
            int i = 0;
            loadFriendCollection:
            try
            {
                i++;
                friends = new SubSonic.Generated.FriendXController().FetchAll();
            }
            catch
            {
                if (i < 10) { goto loadFriendCollection; }
            }
            RSACryptoServiceProvider priv = new RSACryptoServiceProvider();
            priv.FromXmlString(myParent.ffHelper.DBHelper.GetConfig("privatekey"));
            RSACryptoServiceProvider pub = new RSACryptoServiceProvider();
            pub.FromXmlString(myParent.ffHelper.DBHelper.GetConfig("personalkey"));
            foreach (SubSonic.Generated.FriendX f in friends)
            {
                //Client tClient = new NetworkLibrary.Client(f.Hostname,
                //                    (int)f.Port,
                //                    pub.ExportParameters(false),
                //                    priv.ExportParameters(true),
                //                    myParent.ffHelper.GetValueByKey("displayname"));
                //tClient.OnDataReceived += new NetworkLibrary.Common.DataReceived(myParent.server_dataReceivedEvent);
                //tClient.OnConnected += new NetworkLibrary.Common.OnClientConnected(myParent.client_OnConnected);
            }
             */
        //}
        #endregion


        private void Home_Load(object sender, EventArgs e)
        {
            if (lstLists.Items.Count > 0)
            {
                lstLists.SelectedIndex = 0;
            }
            else
            {
                lstLists.DataSource = null;
                lstLists.Refresh();
                lstLists.Items.Add("You have not yet created a playlist");
                lstLists.SelectedIndex = 0;
            }

            //TODO redo friend initialization system.

            //lstFriendChat.ValueMember = "";
            //lstFriendChat.DisplayMember = "";
            //if (lstFriendChat.Items.Count > 0)
            //{
            //    lstFriendChat.SelectedIndex = 0;
            //}
            //else
            //{
            //    lstFriendChat.Items.Add("No friends online.");
            //    lstFriendChat.SelectedIndex = 0;
            //}
        }


        #region shoutbox stuff
        // several methods including the async callback are located in FriendlyFire.css
        private void txtShoutMsg_KeyUp(object sender, KeyEventArgs e)
        {/*
            if (e.KeyCode == Keys.Enter && lstFriendChat.SelectedIndex != -1)
            {
                // send the text to the other guy's show box;
                foreach (Client c in myParent.Clients)
                {
                    if (c.IsConnected)
                    {
                        if (c.BsPublicKey.Equals(((FriendsInAList)lstFriendChat.Items[lstFriendChat.SelectedIndex]).Hash))
                        {
                            // found who we wanna shout to
                            c.SendData(ASCIIEncoding.UTF8.GetBytes(txtShoutMsg.Text), 604); // send the msg un UTF8 to the other guy
                            txtShoutMsg.Text = "";
                        }
                    }
                }
            }*/
        }

        private void LoadShoutBox()
        {
            shoutBox.Text = myParent.ffHelper.DBHelper.GetConfig("shout");
        }
        #endregion

        #region LoadPlayList
        /// <summary>
        /// Loads a playlist from the database
        /// Changed: Aug 2009
        /// </summary>
        private void btnLoadPlaylist_Click(object sender, EventArgs e)
        {
            if (!lstLists.Items.Contains("You have not yet created a playlist"))
            {
                myParent.Srch.playbox.Items.Clear();
                // load items into "playbox"
                foreach (QueueItem q in myParent.ffHelper.DBHelper.GetPlayListAsQueueItemList((long)lstLists.SelectedValue))
                {
                    myParent.Srch.playbox.Items.Add(q);
                }
                myParent.Srch.listName.Text = ((KeyValuePair<long, string>)(lstLists.SelectedItem)).Value;
                myParent.Srch.playbox.SelectedIndex = 0;    // cant be empty by now
                myParent.Video.vactx.playlist.clear();
                myParent.Video.vactx.Visible = true;
                int id = myParent.Video.vactx.playlist.add(((QueueItem)myParent.Srch.playbox.Items[myParent.Srch.playbox.SelectedIndex]).Dir +
                                "\\" + ((QueueItem)myParent.Srch.playbox.Items[myParent.Srch.playbox.SelectedIndex]).Name,
                                ((QueueItem)myParent.Srch.playbox.Items[myParent.Srch.playbox.SelectedIndex]).Name, null);
                myParent.Video.vactx.playlist.playItem(id);
                myParent.tabControl1.SelectedTab = myParent.tabControl1.TabPages[4];
            }
        }
        #endregion
        #region DeletePlayList
        /// <summary>
        /// Delete's a playlist and it's children from the database.
        /// Changed: Aug 2009
        /// </summary>
        private void btnDeleteList_Click(object sender, EventArgs e)
        {          
            if (lstLists.SelectedIndex != -1)
            {
                long listID = Convert.ToInt64(lstLists.SelectedValue);
                int result = myParent.ffHelper.DBHelper.DeletePlayList(listID);

                lstLists.DisplayMember = "Value";
                lstLists.ValueMember = "Key";
                lstLists.DataSource = myParent.ffHelper.DBHelper.GetPlayLists().ToList();
                if (lstLists.Items.Count > 0)
                {
                    lstLists.SelectedIndex = 0;
                }
                else
                {
                    lstLists.DataSource = null;
                    lstLists.Refresh();
                    lstLists.Items.Add("You have not yet created a playlist");
                    lstLists.SelectedIndex = 0;
                }

            }
        }
        #endregion
    }
}
